package org.cypress.rtpack.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.cypress.rtpack.entity.RtpackMoniip;
import org.cypress.rtpack.mapper.RtpackMoniipMapper;
import org.cypress.rtpack.service.IRtpackMoniipService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author getty
 */
@Service
public class RtpackMoniipServiceImpl extends ServiceImpl<RtpackMoniipMapper, RtpackMoniip> implements IRtpackMoniipService {

    @Override
    public RtpackMoniip getByIndex(Integer index) {
        LambdaQueryWrapper<RtpackMoniip> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RtpackMoniip::getIndex, index);     //RtpackMoni需要有getIndex方法，类需要@Data注解
        RtpackMoniip rtpackMoniip = this.getBaseMapper().selectOne(queryWrapper);
        return rtpackMoniip;
    }

    @Override
    @Transactional(readOnly = true)  // 自动管理连接生命周期
    public List<RtpackMoniip> getAll() {
        LambdaQueryWrapper<RtpackMoniip> queryWrapper = new LambdaQueryWrapper<>();
        List<RtpackMoniip> rtpackMoniipList = this.getBaseMapper().selectList(queryWrapper);
        return rtpackMoniipList;
    }

    @Override
    public RtpackMoniip updateByIndex(RtpackMoniip inst) {
        // 1. 参数校验
        if (inst == null || inst.getIndex() == null) {
            throw new IllegalArgumentException("Config or key cannot be null");
        }

        // 2. 检查配置项是否存在
        LambdaQueryWrapper<RtpackMoniip> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RtpackMoniip::getIndex, inst.getIndex());
        RtpackMoniip existing = getOne(queryWrapper);

        if (existing == null) {
            throw new RuntimeException("Config with key [" + inst.getIndex() + "] not found");
        }

        // 3. 保留原始ID（防止前端误传ID导致更新错误记录）
        inst.setIndex(existing.getIndex());

        // 4. 执行更新（MyBatis-Plus的updateById是原子操作）
        boolean success = updateById(inst);

        if (!success) {
            throw new RuntimeException("Update config failed");
        }

        // 5. 返回更新后的完整数据（避免返回前端可能修改过的对象）
        return getByIndex(inst.getIndex());
    }

    @Override
    @Transactional(rollbackFor = Exception.class) // 添加事务控制
    public List<RtpackMoniip> batchUpdateByIndex(List<RtpackMoniip> instList) {
        // 1. 参数校验
        if (CollectionUtils.isEmpty(instList)) {
            throw new IllegalArgumentException("Config list cannot be empty");
        }

        // 2. 检查所有key是否存在
        List<Integer> keys = instList.stream()
                .map(RtpackMoniip::getIndex)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

        if (keys.size() != instList.size()) {
            throw new IllegalArgumentException("Some configs have null keys");
        }

        // 3. 获取现有配置项映射表（一次性查询优化性能）
        Map<Integer, RtpackMoniip> existingMap = listByIndexs(keys).stream()
                .collect(Collectors.toMap(RtpackMoniip::getIndex, Function.identity()));

        // 4. 准备待更新列表（保留原始ID）
        List<RtpackMoniip> toUpdate = instList.stream()
                .peek(config -> {
                    RtpackMoniip existing = existingMap.get(config.getIndex());
                    if (existing == null) {
                        throw new RuntimeException("Config with key [" + config.getIndex() + "] not found");
                    }
                    config.setIndex(existing.getIndex()); // 关键：绑定数据库ID
                })
                .collect(Collectors.toList());

        // 5. 批量更新（MyBatis-Plus的saveOrUpdateBatch）
        if (!updateBatchById(toUpdate)) {
            throw new RuntimeException("Batch update failed");
        }

        // 6. 返回更新后的最新数据
        return (List<RtpackMoniip>) listByIds(toUpdate.stream().map(RtpackMoniip::getIndex).collect(Collectors.toList()));
    }

    // 辅助方法：根据index批量查询
    private List<RtpackMoniip> listByIndexs(List<Integer> idxs) {
        LambdaQueryWrapper<RtpackMoniip> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(RtpackMoniip::getIndex, idxs);
        return list(queryWrapper);
    }

    @Override
    public void truncateTable() {
        // 方式1：使用MyBatis-Plus的物理删除（需在mapper.xml中配置）
        //getBaseMapper().truncateTable();

        // 方式2：逻辑删除（如果表有deleted字段）
        // lambdaUpdate().set(RtpackMoniip::getDeleted, 1).update();
    }

    /**
     * 物理删除所有记录（保留表结构）
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteAllRecords() {
        return getBaseMapper().deleteAllRecords(); // 调用注解方法
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<RtpackMoniip> batchInsert(List<RtpackMoniip> instList) {
        if (CollectionUtils.isEmpty(instList)) {
            return Collections.emptyList();
        }
        saveBatch(instList); // MyBatis-Plus的批量插入
        return instList;
    }
}
